package controllers

import (
	"my-go-project/model"
	"my-go-project/utils/token"
	"net/http"

	"github.com/gin-gonic/gin"
)

func GetFollowList(ctx *gin.Context) {
	var followList []model.UserMessage

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	follow, err := model.GetFocusIDList(int(uid))
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	for _, f := range follow {
		userMessage, err := model.GetUserMessage(int(f.FocusID))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		followList = append(followList, userMessage)
	}
	ctx.JSON(http.StatusOK, followList)
}

func AddFocus(ctx *gin.Context) {
	var focusID model.FollowMini
	if err := ctx.ShouldBindBodyWithJSON(&focusID); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "请求体格式错误！",
		})
		return
	}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	if int(uid) == focusID.FocusID {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "用户不可关注自己！",
		})
		return
	}

	ifFollowed, err := model.IfFollowed(int(uid), focusID.FocusID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	if ifFollowed {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "当前用户已关注！",
		})
		return
	}

	err = model.AddFocus(int(uid), focusID.FocusID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"Response": "添加关注成功！",
	})
}

func MoveFocus(ctx *gin.Context) {
	var focusID model.FollowMini
	if err := ctx.ShouldBindBodyWithJSON(&focusID); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "请求体格式错误！",
		})
		return
	}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	if int(uid) == focusID.FocusID {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "用户不可关注自己！",
		})
		return
	}

	ifFollowed, err := model.IfFollowed(int(uid), focusID.FocusID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	if !ifFollowed {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "当前用户不在关注列表中！",
		})
		return
	}

	err = model.DeleteFocus(int(uid), focusID.FocusID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"Response": "移除关注成功！",
	})
}
